import pyautogui
import pynput
from pynput import mouse
import math
import time

class MouseController:
    def __init__(self):
        self.points = []
        self.listener = None
        # 调整这个系数来改变距离与时间的比例
        # 例如：100像素距离 = 1秒长按时间
        self.time_factor = 0.01
        
    def calculate_distance(self, p1, p2):
        """计算两点之间的距离"""
        return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)
    
    def on_click(self, x, y, button, pressed):
        """鼠标点击事件处理"""
        if button == mouse.Button.right and pressed:
            self.points.append((x, y))
            print(f"记录点 {len(self.points)}: ({x}, {y})")
            
            if len(self.points) == 2:
                # 计算两点距离
                distance = self.calculate_distance(self.points[0], self.points[1])
                # 计算长按时间（秒）
                hold_time = distance * self.time_factor
                
                print(f"两点距离: {distance:.2f} 像素")
                print(f"长按时间: {hold_time:.2f} 秒")
                
                # 移动到第二个点并长按左键
                pyautogui.moveTo(self.points[1][0], self.points[1][1])
                pyautogui.mouseDown(button='left')
                time.sleep(hold_time)
                pyautogui.mouseUp(button='left')
                
                print("长按完成！")
                
                # 重置点列表，准备下一次操作
                self.points = []
                print("\n准备下一次操作...")
                
    def start(self):
        """启动监听器"""
        print("脚本已启动！")
        print("使用方法：")
        print("1. 右键点击第一个点")
        print("2. 右键点击第二个点")
        print("3. 脚本会在第二个点位置模拟左键长按")
        print("4. 按 Ctrl+C 退出程序\n")
        
        with mouse.Listener(on_click=self.on_click) as listener:
            self.listener = listener
            listener.join()

if __name__ == "__main__":
    try:
        # 获取用户输入的time_factor值
        while True:
            try:
                user_input = input("请输入time_factor值 (例如: 0.01): ")
                time_factor = float(user_input)
                if time_factor <= 0:
                    print("time_factor必须大于0")
                    continue
                break
            except ValueError:
                print("请输入有效的数字！")
        
        controller = MouseController()
        controller.time_factor = time_factor
        print(f"已设置time_factor为: {time_factor}")
        controller.start()
    except KeyboardInterrupt:
        print("\n程序已退出")